package com.aaa.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.aaa.controller.BaseController;
import com.aaa.entity.Result;
import com.aaa.entity.system.User;
import com.aaa.service.system.MenuService;
import com.aaa.service.system.UserService;
import com.aaa.utils.MyTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ：肖成杰（1752167034@qq.com）
 * @date ：Created in 2022/8/9 14:43
 * @description：登录跳转
 * @modified By：
 * @version: 1.0
 */
@Controller
public class LoginServlet extends BaseController {

    @Autowired
    UserService userService;
    @Autowired
    MenuService menuService;

    @RequestMapping("login.do")
    @ResponseBody
    public Result login(User user, HttpSession session){
        //根据用户中的用户名和密码进行合法性校验
        User newUser  = userService.queryUserByName(user);
        if(ObjectUtil.isEmpty(newUser)){
            //用户不存在
            return  fail("用户"+user.getUsername()+"不存在");
        }else {
            //用户存在,
            // 1、根据用户将用户的盐值和密文查询出来
            String salt = newUser.getSalt();
            //数据库的密文
            String password = newUser.getPassword();
            // 2、将明文密码加密之后跟第一步的密文对比，一致就是登录成功
            String makePasswordSalt = MyTools.makePasswordSalt(user.getPassword(), salt);
            if(makePasswordSalt.equals(password)){
                //登录成功，根据用户名，查询对应的所有的菜单
                Map<String,Object> menuListMap= menuService.queryMenuByUsername(user.getUsername());
                session.setAttribute("menuListMap",menuListMap);
                session.setAttribute("user",newUser);
                return   success("登录成功");
            }else {
                return  fail("密码错误");
            }
        }
    }

    @RequestMapping("logout.do")
    @ResponseBody
    public ModelAndView logout(ModelAndView modelAndView,HttpSession session){
        //清空session中的所有数据
        session.invalidate();
        modelAndView.setViewName("login");
        return modelAndView;
    }

}